<template>
	<el-dropdown trigger="click">
		<div class="avatar">
      <div class="username">{{ userInfo.userName }}（{{userInfo.roleNames}}）</div>
      <el-icon><CaretBottom /></el-icon>
		</div>
		<template #dropdown>
			<el-dropdown-menu>
        <el-dropdown-item @click="openDialog('roleRef')" divided>
          <el-icon><School /></el-icon>
          <span>切换学校</span>
				</el-dropdown-item>
        <el-dropdown-item @click="openDialog('passwordRef')" divided>
					<el-icon><Edit /></el-icon>
          <span>修改密码</span>
				</el-dropdown-item>
				<el-dropdown-item @click="handleLogout" divided>
					<el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
				</el-dropdown-item>
			</el-dropdown-menu>
		</template>
	</el-dropdown>
  <!-- passwordDialog -->
  <PasswordDialog ref="passwordRef"></PasswordDialog>
  <!-- roleDialog -->
  <RoleDialog ref="roleRef"></RoleDialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { GlobalStore } from "@/stores";
import { logout } from '@/api/modules/login'
import { LOGIN_URL } from "@/config/config";
import { useRouter } from "vue-router";
import PasswordDialog from "./PasswordDialog.vue";
import RoleDialog from "@/views/login/components/RoleList.vue";
import { ElMessageBox, ElMessage } from "element-plus";

const router = useRouter();
const globalStore = GlobalStore();
const userInfo = computed(() => globalStore.userInfo)
// 退出登录
const handleLogout = () => {
	ElMessageBox.confirm("您是否确认退出登录?", "温馨提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning"
	}).then(async () => {
		// 1.调用退出登录接口
		await logout();
		// 2.清除 Token
		globalStore.setToken("");
		globalStore.setUserInfo("");
    router.replace(LOGIN_URL);
		// 3.重定向到登陆页
		ElMessage.success("退出登录成功！");
	});
};

const passwordRef = ref<InstanceType<typeof PasswordDialog> | null>(null);
const roleRef = ref<InstanceType<typeof RoleDialog> | null>(null);
const openDialog = (ref: string) => {
  if (ref == "passwordRef") passwordRef.value?.openDialog();
  if (ref == "roleRef") roleRef.value?.acceptParams(globalStore.schoolList);
};
</script>

<style scoped lang="scss">
.avatar {
  display: flex;
  align-items: center;
	cursor: pointer;
  color: #fff;
  .username {
		margin: 0 6px 0 0;
		font-size: 15px;
	}
	img {
    width: 28px;
	  height: 28px;
	  border-radius: 50%;
    margin-right: 10px;
	}
}
</style>
